package com.hongguowei.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hongguowei.upload.ALiOssTemplate;
import com.hongguowei.upload.OssBo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@RestController
@Slf4j
@RequestMapping("/ImageController")
public class ImageController {
    @Autowired
    private ALiOssTemplate aliOssTemplate;

    @PostMapping("upload")
    public String uploadFile(@RequestPart("file") MultipartFile multipartFile) {

        String originalFilename = multipartFile.getOriginalFilename();
        InputStream fileInputStream;
        try {
            fileInputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            log.error("获取输入流失败:{}", e.getMessage());
            throw new RuntimeException(e);
        }

        if (StringUtils.isBlank(originalFilename)) {
            log.error("文件名不能为空");
            throw new RuntimeException("文件名不能为空");
        }

        OssBo ossBo = new OssBo();
        ossBo.setInputStream(fileInputStream);
        ossBo.setFileName(originalFilename);
        return this.aliOssTemplate.uploadFileToOss(ossBo);
    }
}
